const { url } = require('../../config/index.js') // 接口请求地址
const MD5 = require('../../utils/md5.js') // MD5

/**
 * ******微信支付******
 * 
 * TRADE_NO 流水号
 * TOTAL_FEE 支付金额
 * BODY 商品描述
 * ORDER_NO 订单号
 * resolve promise 成功
 * reject promise 失败
 */
function wxPay(TRADE_NO, TOTAL_FEE, BODY, ORDER_NO, resolve, reject) {
  return new Promise(function (resolve2, reject2) {
    wx.request({
      url: url + 'WXPay/getOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        OPEN_ID: wx.getStorageSync('userInfo').AUTH_INFO.openid,
        TRADE_NO: TRADE_NO,
        TOTAL_FEE: TOTAL_FEE,
        BODY: BODY,
        ISAPP: 1 // 小程序支付标记
      },
      success: res => {
        if (res.data.STATUS_CODE == 1) {
          console.log(res.data)
          // 最后一步 微信支付api
          wx.requestPayment({
            'timeStamp': res.data.timestamp,
            'nonceStr': res.data.noncestr,
            'package': 'prepay_id=' + res.data.prepayid,
            'signType': 'MD5',
            'paySign': res.data.sign,
            'success': function (res) {
              console.log('支付成功')
              console.log(res)
              resolve && resolve(res)
              resolve2 && resolve2(res)
              
            },
            'fail': function (res) {
              console.log(res)
              reject && reject(res)
              reject2 && reject2(res)
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '支付失败',
          })
        }
      }
    })
  })

}

/**
 * ~我的订单~ 与 ~订单详情~ 内发起的内发起支付
 * userId 用户id
 * orderid 订单id
 * cashVolNo 代金券编号
 */
function rePayOrder(userId, orderid, cashVolNo, payWay) {
  let postData = {
    USER_ID: userId,   //用户id
    ORDER_ID: orderid,  //订单id
    PAY_WAY: payWay,  //支付方式 微信
    NEED_INVOICE: 0,  //是否需要发票
    CASH_VOL_NO: cashVolNo // CASH_VOL_NO  //代金券编号
  }
  // console.log(postData)
  // return
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url + 'ServOrderNew/payOffServOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        jsonParams: JSON.stringify(postData)
      },
      success: res => {
        if (res.data.STATUS_CODE == 1) {
          // console.log(res.data)
          if(payWay == 2) {
            /* *****发起微信支付***** */
            wxPay(res.data.TRADE_NO, res.data.TOTAL_FEE, res.data.BODY, res.data.ORDER_NO, resolve, reject);
          } else if (payWay == 9) {
            /* *****余额支付resolve() 弹出密码窗***** */
            resolve(res)
          }
        } else {
          reject(res)
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.RESULT_MSG,
          })
        }
      }
    }) 
  })
}

/**
 * ******余额支付******
 * yuePayInfo 余额支付后台返回的参数
 * pwd password
 */
function yuePay(yuePayInfo, pwd) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url + 'ServOrderNew/pospalNotifyAndUpdateServOrder.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        USER_ID: yuePayInfo.USER_ID,
        TRADE_NO: yuePayInfo.TRADE_NO,
        PASS_WORD: MD5(pwd)
      },
      success: res => {
        console.log(res.data)
        if (res.data.STATUS_CODE == 1) {
          resolve(res.data)
        } else {
          reject(res)
          wx.showModal({
            title: '提示',
            content: res.data.RESULT_MSG,
            showCancel: false
          })
        }
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

// 获取用户的余额
function getYue () {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url + 'pospal/getPospalUserInfo.action',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        USER_ID: wx.getStorageSync('userInfo').USER_ID
      },
      success: res => {
        if (res.data.STATUS_CODE == 1) {
          let amount = res.data.AMOUNT
          resolve(amount)
        } else {
          reject(res.data)
        }
      },
      fail: err => {
        reject(err)
      }
    }) 
  })
}

module.exports = {
  rePayOrder,
  wxPay,
  getYue,
  yuePay
}